<template>
  <div class="video-player-container">
    <div class="video-header">
      <h3>{{ video.title }}</h3>
      <el-button @click="closePlayer" size="small" type="info">关闭</el-button>
    </div>
    <div class="video-wrapper">
      <video 
        ref="videoPlayer"
        class="video-element"
        controls
        @loadedmetadata="onVideoLoad"
        @error="onVideoError"
        @contextmenu.prevent="preventContextMenu"
        :controlsList="'nodownload'"
      >
        <source :src="videoSrc" :type="videoType" v-if="videoSrc">
        您的浏览器不支持视频播放。
      </video>
      <div v-if="!videoSrc" class="loading-message">
        视频加载中...
      </div>
      <div v-if="videoSrc && !isPlaying" class="play-button-container">
        <el-button @click="playVideo" type="primary" size="small">播放视频</el-button>
      </div>
    </div>
    <div class="video-info">
      <p class="video-description">{{ video.description || '无描述' }}</p>
      <div class="video-meta">
        <span>时长: {{ duration }}分钟</span>
        <span>大小: {{ fileSize }}</span>
        <span>上传时间: {{ uploadTime }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElButton } from 'element-plus'

const props = defineProps<{
  video: any
  apiBaseUrl: string
  onClose: () => void
}>()

const videoPlayer = ref<HTMLVideoElement | null>(null)
const videoType = ref('video/mp4')
const isPlaying = ref(false)

// Prevent right-click context menu
const preventContextMenu = (event: Event) => {
  event.preventDefault()
}

// 视频事件处理函数
const playHandler = () => {
  isPlaying.value = true
}

const pauseHandler = () => {
  isPlaying.value = false
}

const endedHandler = () => {
  isPlaying.value = false
}

// 视频源URL
const videoSrc = ref('')

// 获取带认证的视频数据
const fetchVideoWithAuth = async () => {
  if (!props.video || !props.video.url) {
    console.error('Invalid video data')
    return
  }
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.error('No authentication token found')
      return
    }
    
    const fullUrl = props.video.url.startsWith('http') ? 
      props.video.url : 
      `${props.apiBaseUrl}${props.video.url}`
    
    const response = await fetch(fullUrl, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.ok) {
      const blob = await response.blob()
      videoSrc.value = URL.createObjectURL(blob)
    } else {
      console.error('Failed to fetch video:', response.status, response.statusText)
      videoSrc.value = '' // Reset on error
    }
  } catch (error) {
    console.error('Error fetching video:', error)
    videoSrc.value = ''
  }
}

// 计算文件大小
const fileSize = computed(() => {
  if (props.video && props.video.fileSize && props.video.fileSize > 0) {
    const sizeInMB = props.video.fileSize / (1024 * 1024)
    return sizeInMB.toFixed(2) + ' MB'
  }
  return '未知'
})

// 计算上传时间
const uploadTime = computed(() => {
  if (props.video && props.video.createdTime) {
    const date = new Date(props.video.createdTime)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  return '未知'
})

// 计算预估时长
const duration = computed(() => {
  if (props.video && props.video.fileSize && props.video.fileSize > 0) {
    // This is a rough estimation - in a real application, you would get this from video metadata
    // Assuming average bitrate of 1 MB per minute for estimation
    const minutes = Math.round(props.video.fileSize / (1024 * 1024) / 1)
    return minutes > 0 ? minutes.toString() : '未知'
  }
  return '未知'
})

// 视频加载完成时的处理
const onVideoLoad = () => {
  console.log('Video loaded successfully')
}

// 视频加载错误时的处理
const onVideoError = (event) => {
  console.error('Video loading error:', event)
}

// 手动播放视频
const playVideo = () => {
  if (videoPlayer.value) {
    videoPlayer.value.play().catch(error => {
      console.warn('播放失败:', error)
    })
  }
}

// 关闭播放器
const closePlayer = () => {
  if (props.onClose) {
    props.onClose()
  }
}

onMounted(() => {
  // 组件挂载时获取视频数据
  fetchVideoWithAuth()
  
  // 添加视频事件监听器
  if (videoPlayer.value) {
    videoPlayer.value.addEventListener('play', playHandler)
    videoPlayer.value.addEventListener('pause', pauseHandler)
    videoPlayer.value.addEventListener('ended', endedHandler)
  }
})

// 当视频源更新时自动播放
watch(videoSrc, (newSrc) => {
  if (newSrc && videoPlayer.value) {
    // 等待下一帧再尝试播放，确保视频元素已更新
    nextTick(() => {
      // 检查元素是否仍在DOM中
      if (videoPlayer.value && document.contains(videoPlayer.value)) {
        videoPlayer.value.play().catch(error => {
          console.warn('自动播放失败:', error)
        })
      }
    })
  }
})

// 组件销毁时清理blob URL和事件监听器
onUnmounted(() => {
  if (videoSrc.value) {
    URL.revokeObjectURL(videoSrc.value)
  }
  
  // 移除视频事件监听器
  if (videoPlayer.value) {
    videoPlayer.value.removeEventListener('play', playHandler)
    videoPlayer.value.removeEventListener('pause', pauseHandler)
    videoPlayer.value.removeEventListener('ended', endedHandler)
  }
})
</script>

<style scoped>
.video-player-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.video-header h3 {
  margin: 0;
  color: #333;
}

.video-wrapper {
  text-align: center;
  margin-bottom: 15px;
}

.video-element {
  width: 100%;
  max-height: 400px;
  background: #000;
  border-radius: 4px;
}

.loading-message {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #666;
  font-size: 16px;
}

.play-button-container {
  text-align: center;
  margin-top: 10px;
}

.video-info {
  text-align: left;
}

.video-description {
  margin: 10px 0;
  color: #666;
  line-height: 1.5;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

@media (max-width: 768px) {
  .video-player-container {
    padding: 10px;
  }
  
  .video-meta {
    flex-direction: column;
    gap: 5px;
  }
}
</style>